<?php
/**
 * Zend Image Manipulation Module
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.

 * @category   Zimm
 * @package    Zimm
 * @copyright  Copyright (c) 2012 Kristoffer Ingemansson
 * @license    New BSD License
 * @version    $Id: Save.php 4 2012-04-14 12:59:16Z kristoffer.ingemansson@gmail.com $
 */

class Zimm_Model_DbTable_Instruction_Save extends Zimm_Model_DbTable_Instruction_Abstract
{
    /**
     * Save image to $savePath.
     *
     * @param resource $image GD resource
     * @param string $savePath Target save path
     * @param array $params Instruction arguments
     * @return boolean Indicates if image was altered
     */
    protected function _process(&$image, $savePath, $params)
    {
        if (!$savePath) {
            return false;
        }

        if (isset($params['format'])) {
            $quality = isset($params['quality']) ? max(0, min(100, $params['quality'])) : 100;
            switch ($params['format']) {
                case 'png24':
                    imagesavealpha($image, true);
                    $q = 9 - (int)(9 * max(0, min(100, $quality)) / 100);
                    imagepng($image, $savePath, $q , PNG_ALL_FILTERS);
                    break;
                case 'png':
                case 'png8':
                    $colors = 255;
                    if (isset($params['colors'])) {
                        $colors = max(1, min(255, $params['colors']));
                    }
                    imagetruecolortopalette($image, true, $colors);
                    imagesavealpha($image, false);
                    $q = 9 - (int)(9 * max(0, min(100, $quality)) / 100);
                    imagepng($image, $savePath, $q , PNG_ALL_FILTERS);
                    break;
                case 'jpg':
                case 'jpeg':
                    imagejpeg($image, $savePath, $quality);
                    break;
                case 'gif':
                    $colors = 255;
                    if (isset($params['colors'])) {
                        $colors = max(1, min(255, $params['colors']));
                    }
                    imagetruecolortopalette($image, true, $colors);
                    imagesavealpha($image, false);
                    imagegif($image, $savePath);
                    break;
            }
            return true;
        }
        return false;
    }
}